package com.mdc.mansion.core.modules.push.impl;


import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import com.alibaba.fastjson.JSONObject;
import com.mdc.mansion.common.exception.BusinessException;
import com.mdc.mansion.core.common.util.RestaurantSupport;
import com.mdc.mansion.core.modules.push.JPushToClientService;
import com.mdc.mansion.core.modules.system.SysDictService;
import com.mdc.mansion.dataaccess.modules.basedata.entity.PushMessage;
import com.mdc.mansion.dataaccess.modules.restaurant.entity.RestaurantStaff;
import com.mdc.mansion.dataaccess.modules.system.entity.Dict;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Component
public class JPushToClientTagNotifiServiceImpl implements JPushToClientService {
    @Resource
    private SysDictService sysDictService;
    @Override
    public boolean isSupport(PushMessage pushMessage) {
        if(StringUtils.equals(PushMessage.MESSAGE_TYPE.NOTIFI.getVal(),pushMessage.getMessageType())){
            return true;
        }
        return false;
    }

    @Override
    public void sendToClient(PushMessage pushMessage) {
        Dict dict=new Dict();
        dict.setType("jpush_config");
        List<Dict> list = sysDictService.findList(dict);
        String jpushConfig= list.get(0).getValue();
        //{"appKey":"","masterSecret":""}
        JSONObject jsonObject= JSONObject.parseObject(jpushConfig);
        String appKey=jsonObject.getString("appKey");
        String masterSecret=jsonObject.getString("masterSecret");
        JPushClient jpushClient = new JPushClient(masterSecret, appKey, null, cn.jiguang.common.ClientConfig.getInstance());

        int errorCount=0;
        // For push, all you need do is to build PushPayload object.
        Exception ex=null;
        for(int i=1;i<=2;i++){
            pushMessage.setTags(RestaurantSupport.createJpushTag(pushMessage.getRestaurantId(),RestaurantStaff.ROLE_TYPE.SYY.getVal()));
            if(i==1){
                pushMessage.setTags(RestaurantSupport.createJpushTag(pushMessage.getRestaurantId(), RestaurantStaff.ROLE_TYPE.FWY.getVal()));
            }
            PushPayload payload = buildPushObjectAlert(pushMessage);
            try {
                PushResult result = jpushClient.sendPush(payload);
            } catch (APIConnectionException e) {
                ex=e;
            } catch (APIRequestException e) {
                ex=e;
            }
        }
        if(errorCount>=2){throw new BusinessException(ex);}
    }

    private PushPayload buildPushObjectAlert(PushMessage pushMessage) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.tag(pushMessage.getTags()))
//                .setNotification(Notification.android(ALERT, pushMessage.getMessage(), null))
                .setMessage(Message.newBuilder()
                        .setMsgContent(pushMessage.getMessage())
                        .addExtra("from", "JPush")
                        .build())
                .build();
    }
}
